package com.wxy.demo.client;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wangxiaoyuan
 * 2021/3/24 14:17
 **/
public class RestClient {
    public static void main(String[] args) throws IOException {
        String requestUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
        String method = "/getSupportCity";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("byProvinceName", "ALL");
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建http Post请求
        HttpPost httpPost = new HttpPost(requestUrl+method);
        CloseableHttpResponse response = null;
        try {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            List<BasicNameValuePair> pairList = new ArrayList<>();
            parameters.forEach((k, v) -> pairList.add(new BasicNameValuePair(k, v.toString())));
            httpPost.setEntity(new UrlEncodedFormEntity(pairList));
            response = httpClient.execute(httpPost);
            // 判断返回状态是否为200
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            } else {
                System.out.println("调用失败：code=" + statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                response.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
    }


}
